﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace T.Basic.API.ServiceCollectionExtensions
{
    public static class ServiceCollectionExtension
    {
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
         
                //  添加JWT验证        认证使用             配置                服务
                builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
                {

                    // 私钥             字节数组       编码           配置         JwtTokenOptions            安全密钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtTokenOptions:SecurityKey"]);
                    // 验证参数         令牌验证参数      
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        // 验证发布者
                        ValidateIssuer = true,
                        // 发布者信息
                        ValidIssuer = builder.Configuration["JwtTokenOptions:Issuer"],

                        // 验证接收者
                        ValidateAudience = true,
                        // 接收者
                        ValidAudience = builder.Configuration["JwtTokenOptions:Audience"],

                        // 验证是否过期
                        ValidateLifetime = false,


                        // 验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                    };
                });
            }
        
    }


}
